package com.example.bzh.gamecat.ui.society;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.bzh.gamecat.R;
import com.example.bzh.gamecat.base.BaseFragment;
import com.example.bzh.gamecat.bean.ActiveListBean;
import com.example.bzh.gamecat.bean.AdvertListBean;
import com.example.bzh.gamecat.bean.BabyListBean;
import com.example.bzh.gamecat.bean.DataBean;
import com.example.bzh.gamecat.bean.GameListBean;
import com.example.bzh.gamecat.bean.GuildListBean;
import com.example.bzh.gamecat.bean.SocietyBean;
import com.example.bzh.gamecat.ui.society.allsociety.AllSocietyActivity;
import com.example.bzh.gamecat.ui.society.babysociety.SocietyBabyActivity;
import com.lidroid.xutils.BitmapUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 */
public class SocietyFragment extends BaseFragment implements SocietyContract.IView{


    @BindView(R.id.iv_top_menu_society)
    ImageView ivTopMenuSociety;
    @BindView(R.id.image_search_society)
    TextView imageSearchSociety;
    @BindView(R.id.vp_society)
    ViewPager vpSociety;
    @BindView(R.id.tv_allsociety_society)
    TextView tvAllsocietySociety;
    @BindView(R.id.image_hotone_society)
    ImageView imageHotoneSociety;
    @BindView(R.id.tv_hotone_society)
    TextView tvHotoneSociety;
    @BindView(R.id.relative_message)
    RelativeLayout relativeMessage;
    @BindView(R.id.image_hottwo_society)
    ImageView imageHottwoSociety;
    @BindView(R.id.tv_hottwo_society)
    TextView tvHottwoSociety;
    @BindView(R.id.relative_society)
    RelativeLayout relativeSociety;
    @BindView(R.id.image_hotthree_society)
    ImageView imageHotthreeSociety;
    @BindView(R.id.tv_hotthree_society)
    TextView tvHotthreeSociety;
    @BindView(R.id.relative_live)
    RelativeLayout relativeLive;
    @BindView(R.id.image_hotfour_society)
    ImageView imageHotfourSociety;
    @BindView(R.id.tv_hotfour_society)
    TextView tvHotfourSociety;
    @BindView(R.id.relative_cattery)
    RelativeLayout relativeCattery;
    @BindView(R.id.tv_allbaby_society)
    TextView tvAllbabySociety;
    @BindView(R.id.iv_babyone_society)
    ImageView ivBabyoneSociety;
    @BindView(R.id.iv_babytwo_society)
    ImageView ivBabytwoSociety;
    @BindView(R.id.iv_babythree_society)
    ImageView ivBabythreeSociety;
    @BindView(R.id.gridlayout_allplay_society)
    GridView gridviewAllplaySociety;
    @BindView(R.id.listview_move_society)
    ListView listviewMoveSociety;

    @BindView(R.id.tv_guide_society)
    TextView tvGuideSociety;
    @BindView(R.id.tv_use_manual_society)
    TextView tvUseManualSociety;
    private SocietyContract.IModel model;
    private SocietyContract.IPresenter presenter;

    private int count = 0;
    private AutoRunTask autoTask = new AutoRunTask();
    private final int VIEW_PAGER = 0,VIEWPAGER_CORRENT = 1,HOT_SOCIETY = 2,BABY_SOCIETY = 3,ALLGAME_SOCIETY = 4,ACTIVE_SOCIETY = 5;


    public SocietyFragment() {
        // Required empty public constructor
    }

    //通过Handler得到数据
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case VIEW_PAGER:
                    initHeadViewPager(msg);
                    break;
                case VIEWPAGER_CORRENT:
                    int index = msg.arg1;
                    vpSociety.setCurrentItem(index);
                    break;
                case HOT_SOCIETY:
                    initHotSociety(msg);
                    break;
                case BABY_SOCIETY:
                    initBabySociety(msg);
                    break;
                case ALLGAME_SOCIETY:
                    initAllGame(msg);
                    break;
                case ACTIVE_SOCIETY:
                    initActive(msg);
                    break;
            }

        }
    };

    //设置公会活动
    private void initActive(Message msg) {
        List<ActiveListBean> activeListBeens = (List<ActiveListBean>) msg.obj;
        listviewMoveSociety.setAdapter(new ActiveListAdapter(activeListBeens));
    }

    //设置大家都在玩
    private void initAllGame(Message msg) {
        List<GameListBean> gameListBeen = (List<GameListBean>) msg.obj;
        GameGridAdapter adapter = new GameGridAdapter(gameListBeen,getActivity());
        gridviewAllplaySociety.setAdapter(adapter);
    }

    //设置公会宝贝
    private void initBabySociety(Message msg) {
        List<BabyListBean> babyListBeen = (List<BabyListBean>) msg.obj;
        List<ImageView> imageViews = new ArrayList<>();
        imageViews.add(ivBabyoneSociety);
        imageViews.add(ivBabytwoSociety);
        imageViews.add(ivBabythreeSociety);
        for (int i = 0; i < babyListBeen.size(); i++) {
            String headphoto = babyListBeen.get(i).getHeadphoto();
            Glide.with(getActivity()).load(headphoto).into(imageViews.get(i));
        }
    }

    //设置人气公会
    private void initHotSociety(Message msg) {
        final List<GuildListBean> guildListBean = (List<GuildListBean>) msg.obj;
        Log.i("TAG","guildListBean================="+guildListBean.size());
        List<ImageView> imageViews = new ArrayList<>();
        imageViews.add(imageHotoneSociety);
        imageViews.add(imageHottwoSociety);
        imageViews.add(imageHotthreeSociety);
        imageViews.add(imageHotfourSociety);
        List<TextView> textViews = new ArrayList<>();
        textViews.add(tvHotoneSociety);
        textViews.add(tvHottwoSociety);
        textViews.add(tvHotthreeSociety);
        textViews.add(tvHotfourSociety);
        for (int i = 0; i < guildListBean.size(); i++) {
            String iconUrl = guildListBean.get(i).getIconUrl();
            String catMallName = guildListBean.get(i).getCatMallName();
            textViews.get(i).setText(catMallName);
            Glide.with(getActivity()).load(iconUrl).into(imageViews.get(i));
            final int finalI = i;
            imageViews.get(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getActivity(),SecondActivity.class);
                    intent.putExtra("weburl",guildListBean.get(finalI).getUrl());
                    startActivity(intent);
                }
            });
        }
    }

    //设置头部ViewPager的方法
    private void initHeadViewPager(Message msg) {
        final List<AdvertListBean> viewpagerList = (List<AdvertListBean>) msg.obj;
        ViewPagerAdapter adapter = new ViewPagerAdapter(viewpagerList, getActivity());
//        for (int i = 0; i < viewpagerList.size(); i++) {
//            View points = new View(getActivity());
//            points.setBackgroundResource(R.drawable.circle_16px_on);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(18, 18);
//            params.leftMargin = 5;
//            points.setLayoutParams(params);
//            if (recommendLlPoints.getChildCount() <= viewpagerList.size()) {
//                recommendLlPoints.addView(points);
//            } else {
//                recommendLlPoints.removeView(points);
//            }
//
//        }
//        recommendLlPoints.getChildAt(0).setBackgroundResource(R.drawable.circle_16px);
        vpSociety.setAdapter(adapter);
        vpSociety.setCurrentItem(10000 * viewpagerList.size());
//        vpSociety.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
//            @Override
//            public void onPageSelected(int position) {
//                for (int i = 0; i < recommendLlPoints.getChildCount(); i++) {
//                    recommendLlPoints.getChildAt(i).setBackgroundResource(R.drawable.circle_16px_on);
//                    if (i == position % viewpagerList.size()) {
//                        recommendLlPoints.getChildAt(i).setBackgroundResource(R.drawable.circle_16px);
//                    }
//                }
//            }
//        });

        //开始线程任务
        if (count == 0) {
            autoTask.startRun();
            count = 1;
        }

        //处理ViewPager的触摸事件
        vpSociety.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        autoTask.stopRun();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                        autoTask.startRun();
                        break;
                }

                //不返回false回调用两次
                return false;
            }
        });

    }

    //viewpager自动轮播
    class AutoRunTask implements Runnable {

        private int delayTime = 3000;
        private boolean isStart = false;

        //开始线程任务
        public void startRun() {
            if (!isStart) {
                //关闭之前所有正在执行的任务
                handler.removeCallbacks(this);
                isStart = true;
                handler.postDelayed(this, delayTime);
            }
        }

        //停止线程的方法
        public void stopRun() {
            if (isStart) {
                isStart = false;
                handler.removeCallbacks(this);
            }
        }

        @Override
        public void run() {

            //得到当前页
            int currentItem = vpSociety.getCurrentItem();
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = ++currentItem;
            handler.sendMessage(msg);
            //递归形成循环
            handler.postDelayed(this, delayTime);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_society, container, false);
        ButterKnife.bind(this, view);
        model = new SocietyModel();
        presenter = new SocietyPresenter(model,this);
        presenter.initData(initParams());
        return view;
    }

//    @OnClick({R.id.iv_top_menu_society, R.id.image_search_society, R.id.tv_allsociety_society, R.id.image_hotone_society, R.id.tv_hotone_society, R.id.relative_message, R.id.image_hottwo_society, R.id.tv_hottwo_society, R.id.relative_society, R.id.image_hotthree_society, R.id.tv_hotthree_society, R.id.relative_live, R.id.image_hotfour_society, R.id.tv_hotfour_society, R.id.relative_cattery, R.id.tv_allbaby_society, R.id.iv_babyone_society, R.id.iv_babytwo_society, R.id.iv_babythree_society, R.id.gridlayout_allplay_society, R.id.creat_society, R.id.tv_guide_society, R.id.tv_use_manual_society})
    @Override
    public int getLayoutId() {
        return super.getLayoutId();
    }

    @Override
    public void initView() {
        super.initView();

    }

    @Override
    public void initData() {
        super.initData();

    }

    private HashMap<String, String> initParams() {
        HashMap<String, String> params = new HashMap<>();
        params.put("apiVersion","215");
        params.put("channelId","baidu");
        params.put("devicesId","867581020760386");
        params.put("terminalName","8676-A01");
        params.put("terminalType","2");
        params.put("token","01a30e837881ad7a17b8fce9def84956");
        params.put("version","2.1.6");
        params.put("methodName","guild_guildHomePage");
        return params;
    }

    @OnClick({R.id.iv_top_menu_society, R.id.image_search_society, R.id.tv_allsociety_society, R.id.image_hotone_society, R.id.tv_hotone_society, R.id.relative_message, R.id.image_hottwo_society, R.id.tv_hottwo_society, R.id.relative_society, R.id.image_hotthree_society, R.id.tv_hotthree_society, R.id.relative_live, R.id.image_hotfour_society, R.id.tv_hotfour_society, R.id.relative_cattery, R.id.tv_allbaby_society, R.id.iv_babyone_society, R.id.iv_babytwo_society, R.id.iv_babythree_society, R.id.tv_guide_society, R.id.tv_use_manual_society})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_top_menu_society://顶部菜单按钮
                break;
            case R.id.image_search_society://搜索
                break;
            case R.id.tv_allsociety_society://全部公会
                startActivity(new Intent(getActivity(), AllSocietyActivity.class));
                break;
            case R.id.image_hotone_society://人气1
                break;
            case R.id.image_hottwo_society://人气2
                break;
            case R.id.image_hotthree_society://人气3
                break;
            case R.id.image_hotfour_society://人气4
                break;
            case R.id.tv_allbaby_society://全部宝贝
                startActivity(new Intent(getActivity(), SocietyBabyActivity.class));
                break;
            case R.id.iv_babyone_society://宝贝1
                break;
            case R.id.iv_babytwo_society://宝贝2
                break;
            case R.id.iv_babythree_society://宝贝3
                break;
            case R.id.tv_guide_society://公会指引
                break;
            case R.id.tv_use_manual_society://使用手册
                break;
        }
    }

    //得到网络访问返回的数据
    @Override
    public void OnSeccessGetSociety(SocietyBean societyBean) {

        final DataBean dataBean = societyBean.getData();
        Log.i("TAG","advertList=============="+dataBean.getAdvertList().size());
        Message viewPagerMessage = handler.obtainMessage(VIEW_PAGER,dataBean.getAdvertList());
        handler.sendMessage(viewPagerMessage);

        Message hotSocietyMessage = handler.obtainMessage(HOT_SOCIETY,dataBean.getGuildList());
        handler.sendMessage(hotSocietyMessage);

        Message babyMessage = handler.obtainMessage(BABY_SOCIETY,dataBean.getBabyList());
        handler.sendMessage(babyMessage);

        Message allGameMessage = handler.obtainMessage(ALLGAME_SOCIETY,dataBean.getGameList());
        handler.sendMessage(allGameMessage);

        Message activeMessage = handler.obtainMessage(ACTIVE_SOCIETY,dataBean.getActiveList());
        handler.sendMessage(activeMessage);

//        handler.post(new Runnable() {
//            @Override
//            public void run() {
//
//            }
//        });

    }

    @Override
    public void OnFailGetSociety(final String str) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getActivity(),str,Toast.LENGTH_SHORT).show();
            }
        });
    }
}
